programming4us
           
 
 
Programming

Parallel Programming with Microsoft Visual Studio 2010 : Task Parallelism - Cancellation

- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019
8/18/2011 3:49:58 PM
The sort algorithm sample code in the preceding section allows the three sort algorithms to run to completion. But logically, because all the sort algorithms wind up with the same results, you need to sort the integer collection only once—the fastest way possible. When the fastest sort completes, you can cancel the other sorts. The .NET Framework 4 introduced the concept of cooperative cancellation, which is a consistent model for cancelling tasks. As the name implies, the model requires cooperation from running tasks. Tasks are responsible for regularly checking for a cancellation request. After a cancellation request has been received, a task should perform a timely and orderly shutdown. Checking for cancellation might require polling, and that can easily become a performance sink. For this reason, if it is required, be careful when implementing a polling strategy.

Here are the steps required for the cooperative cancellation model:

  1. Create an instance of the CancellationTokenSource class, which is a wrapper for a cancellation token.

  2. Pass the actual cancellation token (the CancellationTokenSource.Token property) as a parameter to the cooperating tasks.

  3. From the original thread, call the CancellationTokenSource.Cancel method to make a cancellation request.

  4. In the task, check the CancellationToken.IsCancellationRequested property for a cancellation request.

  5. After preparing for cancellation, for example by preserving state information, the task should call the CancellationToken.ThrowIfCancellationRequest method. This throws the OperationCanceledException exception and cancels the task.

  6. You can inspect whether a task was canceled. Check Task.Status for TaskStatus.Canceled.

The use of CancellationTokenSource and CancellationToken types is not restricted to tasks.

The next tutorial demonstrates the cooperative model for cancellation. In this example, you will create a CancellationToken that is passed into a task. In the task, you will periodically check for a cancellation request.

Create a task that throws a cancellation exception

In this procedure, the joining thread catches and handles the unhandled exception.

  1. Create a console application. Before the Main function, add a DoSomething method. To emulate a compute-bound task, the task will simply spin and burn processor cycles. This is done with the Thread.SpinWait method.

    static void DoSomething() { Thread.SpinWait(4000); }

  2. In the Main function, create a CancellationTokenSource object. Afterward, initialize a cancellation token with the CancellationTokenSource.Token property.

    CancellationTokenSource cancellationSource =
    new CancellationTokenSource();
    CancellationToken token = cancellationSource.Token;

  3. Start a try/catch block for handling exceptions.

    try {

  4. You can now create and start a new task by using the TaskFactory.StartNew method. Initialize the task with a lambda expression.

    Task TaskA=Task.Factory.StartNew(() => {

  5. In the lambda expression, you need a while loop. In the loop, call the compute-bound method. Check whether an exception is requested by using the CancellationToken.IsCancellationRequested property. If cancellation is requested, throw a cancellation exception. Notice that you also pass the cancellation token to the task as the last parameter of the StartNew method.

    while (true) {
    DoSomething();
    if (token.IsCancellationRequested) {

    token.ThrowIfCancellationRequested();
    }
    }}, token);

  6. In the joining thread, cancel the task. Then wait for the task to complete and observe the cancellation exception.

    cancellationSource.Cancel();

    TaskA.Wait(); }

  7. In the catch block, catch the cancellation exception and display the message.

  8. Build and run the application.

Here is the complete application.

    static void Main(string[] args)
{
CancellationTokenSource cancellationSource =
new CancellationTokenSource();
CancellationToken token = cancellationSource.Token;
try
{
Task TaskA=Task.Factory.StartNew(() =>
{
while (true)
{
DoSomething();
if (token.IsCancellationRequested)
{
token.ThrowIfCancellationRequested();
}
}
}, token);
cancellationSource.Cancel();
TaskA.Wait();
}
catch (AggregateException ex)
{
Console.WriteLine(ex.InnerException.Message);
}
}
}


1. A Cancellation Example

Here is the sample code to implement cancellation in the bubble sort region of the sorting application. Similar changes can be made in the regions for the insertion and pivot sorts. The three sorting tasks are given the same cancellation token. Because they share the same token, all of the sorting algorithms can be cancelled as a group. For this reason, you create the cancellation token only once before entering the sort regions.

CancellationTokenSource cancellationSource =
new CancellationTokenSource();
CancellationToken token = cancellationSource.Token;

// Bubble Sort Region

List<int> bubbleList = integerList.ToList();
Task taskBubbleSort = new Task(() => {
sortBarrier.SignalAndWait();
using (new SortResults("Bubble Sort")){
SortAlgorithms.BubbleSort(bubbleList, token);
}
}, token);
taskBubbleSort.Start();

Because each sort is different, cancellation polling occurs in different locations in each sort algorithm. When a cancellation request is detected, the code throws an OperationCanceledException exception and cancels the task.

Here is the sample code for actually canceling the sort algorithms. The joining thread calls WaitAny. Unlike WaitAll, WaitAny will return when the fastest task finishes, at which time you can cancel the other sort algorithms that are still running, by calling CancellationTokenSource.Cancel.

Task.WaitAny(new Task[] { taskBubbleSort, taskInsertionSort, taskPivotSort });
cancellationSource.Cancel();
Other -----------------
- Parallel Programming with Microsoft Visual Studio 2010 : Task Parallelism - Sort Examples
- jQuery 1.3 : DOM Manipulation - Wrapping elements & Copying elements
- iOS SDK : Debugging (part 4) - Instruments—Leaks
- iOS SDK : Debugging (part 3) - NSZombieEnabled
- iOS SDK : Debugging (part 2) - Watchpoints
- iOS SDK : Debugging (part1 )
- iOS SDK : Installing Applications on an iPhone
- Software Testing with Visual Studio Team System 2008 : Web Testing - Recording a test
- Software Testing with Visual Studio Team System 2008 : Unit testing web services & Code coverage unit test
- .NET Debugging : Introduction to the Tools - SOS & SOSEX
- .NET Debugging : CLR 4.0 - Synchronization & Interoperability
- iPhone Programming : Connecting to the Network - Getting Data from the Internet
- iPhone Programming : Connecting to the Network - Sending Email
- Programming Excel with VBA and .NET : Tasks in Visual Basic - Check Results
- Programming Excel with VBA and .NET : Tasks in Visual Basic - Read and Write Files
- Programming Excel with VBA and .NET : Tasks in Visual Basic - Get Dates and Times
- Programming Excel with VBA and .NET : Tasks in Visual Basic - Work with Text
- A Technical Overview of the Mobile Web : THE TECHNICAL CHALLENGES OF MOBILE DEVICES (part 2)
- A Technical Overview of the Mobile Web : THE TECHNICAL CHALLENGES OF MOBILE DEVICES (part 1) - Physical Constraints
- Parallel Programming with Microsoft Visual Studio 2010 : Task Parallelism - Unhandled Exceptions in Tasks
 
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
programming4us programming4us